<template>
  <div style="padding:30px;">
    <Breadcrumb />
    <el-card class="box-card">
      <el-button type="primary" @click="addRoleVisible = true">添加角色</el-button>
      <el-table
        class="table"
        :data="roleList"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              :show-header="false"
              :data="props.row.children"
              empty-text=""
            >
              <el-table-column
                prop="authName"
                width="200"
              >
                <template slot-scope="props1">
                  <el-tag
                    disable-transitions
                  >{{ props1.row.authName }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column>
                <template slot-scope="props2">
                  <el-table
                    :show-header="false"
                    :data="props2.row.children"
                    empty-text=""
                  >
                    <el-table-column prop="authName">
                      <template slot-scope="props3">
                        <el-tag
                          disable-transitions
                          type="success"
                        >{{ props3.row.authName }}</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column>
                      <template slot-scope="props4">
                        <el-table
                          :show-header="false"
                          :data="props4.row.children"
                          empty-text=""
                        >
                          <el-table-column prop="authName">
                            <template slot-scope="props5">
                              <el-tag
                                closable
                                type="danger"
                                disable-transitions
                                @close="onDel(props.row,props5.row)"
                              >{{ props5.row.authName }}</el-tag>
                            </template>
                          </el-table-column>
                        </el-table>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="#"
          width="50"
        />
        <el-table-column
          prop="roleName"
          label="角色名称"
        />
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        />
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-row class="btns">
              <el-button icon="el-icon-edit" type="primary" @click="editUserInfo(scope.row)">编辑</el-button>
              <el-button icon="el-icon-delete" type="danger" @click="deleteUser(scope.row)">删除</el-button>
              <el-button icon="el-icon-setting" type="warning" @click="allotRole(scope.row)">分配权限</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增角色弹层 -->
    <el-dialog
      :title="addRoleForm.id?'编辑角色':'新增角色'"
      :visible.sync="addRoleVisible"
      width="50%"
      @close="dialogClose"
    >
      <el-form ref="form" :model="addRoleForm" :rules="roleForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSava">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹层 -->
    <el-dialog
      title="分配权限"
      :visible.sync="allotDialog"
      width="50%"
      @close="close"
    >
      <el-tree
        ref="tree"
        :data="authorityData"
        :show-checkbox="true"
        node-key="id"
        :props="defaultProps"
        :default-expand-all="true"
        :default-checked-keys="checkArr"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialog = false">取 消</el-button>
        <el-button type="primary" @click="roleAllotAuthorization">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { getAllAuthority } from '@/api/departments.js'
import { getRole, addRole, editRole, deleteRole, roleAuthorization, deleteRoleAuthorization } from '@/api/role.js'

export default {
  name: 'Role',
  components: {
    Breadcrumb
  },
  data() {
    return {
      allotDialog: false,
      roleList: [],
      tableData: [],
      addRoleVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      roleForm: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限弹层数据
      authorityData: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      checkArr: [],
      roleId: '' // 分配权限要发送的角色id
    }
  },
  created() {
    this.loadRole()
  },

  methods: {
    // 获取角色列表
    async loadRole() {
      const res = await getRole()
      this.roleList = res
    },
    // 点击了确定
    async onSava() {
      try {
        if (this.addRoleForm.id) {
          // 编辑
          await editRole(this.addRoleForm)
          this.$message.success('编辑成功')
        } else {
          // 添加
          await addRole(this.addRoleForm)
          this.$message.success('添加成功')
        }
        this.addRoleVisible = false
        this.loadRole()
      } catch (err) {
        console.log(err)
      }
    },
    // 点击编辑
    editUserInfo(data) {
      this.addRoleForm = data
      this.addRoleVisible = true
    },
    // 关闭弹层
    dialogClose() {
      this.$refs.form.resetFields()
      this.addRoleForm = {
        roleName: '',
        roleDesc: ''
      }
    },
    // 删除角色
    deleteUser(data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteRole(data.id)
          this.$message.success('删除成功')
          this.loadRole()
        } catch (err) {
          console.log(err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配权限 data是每一行的数据
    async allotRole(data) {
      this.allotDialog = true
      const res = await getAllAuthority('tree')
      this.authorityData = res
      this.roleId = data.id
      this.pitchCheckbox(data, this.checkArr)
    },
    // 递归 找到渲染tree的复选框的id
    pitchCheckbox(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.pitchCheckbox(item, arr)
      })
    },
    // 关闭分配权限弹层
    close() {
      this.checkArr = []
    },
    // 点击分配授权弹层 的确定
    async roleAllotAuthorization() {
      const check = await this.$refs.tree.getCheckedKeys()
      console.log(check.join(','))
      try {
        await roleAuthorization(this.roleId, check.join(','))
        this.allotDialog = false
        this.roleId = ''
        this.$message.success('分配成功')
        this.loadRole()
      } catch (err) {
        console.log(err)
      }
    },
    // 删除权限 data1角色信息 data2 要删除的信息
    async onDel(data1, data2) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteRoleAuthorization(data1.id, data2.id)
          this.$message.success('删除成功')
          this.loadRole()
        } catch (err) {
          console.log(err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}

</script>

<style scoped lang='scss'>
.el-card {
  margin-top: 15px;
  .table {
  margin-top: 15px;
    i {
      margin-left: 5px;
    }
  }
  .btns {
    display: flex;
    .el-button {
      // width: 44px;
      padding: 0 10px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>

